package tjs.org.springLoader.fileWatch;

import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;
import tjs.org.springLoader.config.AutoReloaderProperties;
import tjs.org.springLoader.config.DoAutoReloader;
import tjs.org.springLoader.reloader.ChangeClassReloader;

import java.io.File;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by Nicky.Tang on 2021/9/29 11:52 下午
 *
 * @since 02.12.10
 */
public class FileSystemWatcher {

    private static ExecutorService fixedThreadPool = Executors.newCachedThreadPool();

    private DoAutoReloader doAutoReloader;
    private ChangeClassReloader changeClassReloader;

    public FileSystemWatcher(DoAutoReloader doAutoReloader) {
        this.doAutoReloader = doAutoReloader;
        this.changeClassReloader = new ChangeClassReloader();
    }

    public static void main(String[] args) {
        // FileSystemWatcher.start(null, null, 1000, "/Users/piangpiang/Documents/my-workspace/my-mayun/tjs-org/tjs-spring-loader/target/classes/tjs");
    }

    private void start(long interval, String path) {
        try {
            //构造观察类主要提供要观察的文件或目录，当然还有详细信息的filter
            FileAlterationObserver observer = new FileAlterationObserver(new File(path), (File pathname) -> {
                if (pathname.getPath().indexOf(".class") != -1 || pathname.isDirectory()) {
                    return true;
                }
                return false;
            });
            //构造收听类 没啥好说的
            FileListenerAdaptor listener = new FileListenerAdaptor(this.doAutoReloader.getReloaders(), this.changeClassReloader);
            //为观察对象添加收听对象
            observer.addListener(listener);
            //配置Monitor，第一个参数单位是毫秒，是监听的间隔；第二个参数就是绑定我们之前的观察对象。
            FileAlterationMonitor fileMonitor = new FileAlterationMonitor(interval, new FileAlterationObserver[]{observer});
            //启动开始监听
            fileMonitor.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void start() {
        AutoReloaderProperties properties = this.doAutoReloader.getAutoReloaderProperties();
        for (String path : properties.getClassPathes()) {
            fixedThreadPool.execute(() -> {
                this.start(properties.getInterval(), path);
            });
        }
    }
}
